package com.thx.information.action;

import com.thx.common.struts2.CurdAction;
import com.thx.information.model.InfoColumn;
import com.thx.information.model.InfoVoteItem;
import com.thx.information.model.InfoVoteLog;
import com.thx.information.service.ColumnService;
import com.thx.information.service.InfoVoteItemService;
import com.thx.information.service.InfoVoteLogService;
import com.thx.information.service.InfomationService;
import com.thx.information.view.InformationView;
import com.thx.log.LogUtil;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import java.util.Date;


@ParentPackage(value = "gloab-package")
@Namespace(value = "/information")
@Action(value = "vote",
    results = {@Result(name = "list", location = "/pages/information/vote/list.jsp"),
        @Result(name = "input", location = "/pages/information/vote/input.jsp"),
        @Result(name = "json", type = "json", params = {"root", "result"})},
    interceptorRefs = {@InterceptorRef(value = "topDtStack"),
        @InterceptorRef(value = "pageInterceptor", params = {"includeMethods", "list"}),})
@Controller
@Scope("prototype")
public class VoteAction extends CurdAction<InfoVoteItem> {


  private static final long serialVersionUID = 1L;
  private static final Logger logger = LoggerFactory.getLogger(CommentLogAction.class);

  @Autowired
  private InfoVoteItemService service;

  @Autowired
  private InfomationService infomationService;
  
  @Autowired
  private InfoVoteLogService infoVoteLogService;

  @Autowired
  private ColumnService columnService;

  private String ids;
  private String treeNodes;
  private String pid;
  private String searchName;

  // 查看信息详情
  private InfoColumn belongInfoColumn; // 信息所属分类对象
  private InformationView view; // 信息视图对象


  // 参与投票传递的投票ids
  private String voteItemIds;
  
  // 测试数据
  private Long enterpriseId = 181L;
  private Long personnelId = 1048L;
  private String personnelName = "管理员";
  private String deptName = "部门";
  private Long depId = 1L;
  private Long role = 1L;
  private Boolean ifAdmin = true;

  protected void doList() {
    try {
      if (StringUtils.isNotBlank(id)) {
        logger.info("<进入>:投票统计信息管理方法");
        logger.info("<入参>:所属信息id={}", id);
        Long infoId = NumberUtils.toLong(id);

        view = infomationService.findViewByInfoId(infoId);
        Long tcolumnId = view.getInformation().getColumnId();
        if (tcolumnId != null && tcolumnId.longValue() != 0) {
          belongInfoColumn = columnService.get(tcolumnId);
        }

        logger.info("<出参>:所属信息view={}", view);
      }
    } catch (Exception e) {
      if (StringUtils.isNotBlank(id)) {
        LogUtil.log("投票统计信息管理", LogUtil.ACTION_UPDATE, LogUtil.RESULT_FAIL, "修改信息");
        logger.error("<错误>:查询异常{}", e);
      }
    }
  }

  /**
   * 新增、修改显示页面.
   * 
   */
  public String input() {
    logger.debug("<进入>:投票修改/新增跳转方法");
    logger.info("<入参>:pid={},id={}", pid, id);
    try {
      if (StringUtils.isNotBlank(id)) {
        entity = service.get(Long.parseLong(id));
      }
      logger.debug("<出参>查询结果{}：", entity);
    } catch (Exception e) {
      logger.error("<错误>:查询异常");
    }
    return "input";
  }

  /**
   * 新增修改方法.
   */
  public void doSave() {
    try {
      if (StringUtils.isBlank(id)) {
        logger.debug("<进入>:投票管理新增方法");
        logger.info("<入参>:新增数据={}", entity);
        Long infoId = NumberUtils.toLong(pid);
        InfoVoteItem entityd = new InfoVoteItem();
        BeanUtils.copyProperties(entity, entityd);
        entityd.setInfoId(infoId);
        service.save(entityd);
        setResult(SUCCESS, "新增成功！");
        LogUtil.log("投票信息管理", LogUtil.ACTION_UPDATE, LogUtil.RESULT_SUCCESS, "新增信息");
      } else {
        logger.debug("<进入>:投票管理修改方法");
        logger.info("<入参>:修改信息id={}", entity);
        InfoVoteItem entityd = service.get(Long.parseLong(id));
        BeanUtils.copyProperties(entity, entityd, new String[] {"voteItemId", "infoId"});
        service.update(entityd);
        setResult(SUCCESS, "修改成功！");
        LogUtil.log("投票信息管理", LogUtil.ACTION_UPDATE, LogUtil.RESULT_SUCCESS, "修改信息");
      }
    } catch (Exception e) {
      if (StringUtils.isNotBlank(id)) {
        LogUtil.log("投票信息管理", LogUtil.ACTION_UPDATE, LogUtil.RESULT_FAIL, "修改信息");
        logger.error("<错误>:修改异常{}", e);
      } else {
        LogUtil.log("投票信息管理", LogUtil.ACTION_UPDATE, LogUtil.RESULT_FAIL, "新增信息");
        logger.error("<错误>:新增异常{}", e);
      }
    }
  }

  /**
   * 参与投票
   * 
   * @return
   */
  public String joinVote() {
    try {
      logger.debug("<进入>:参与投票");
      logger.info("<入参>:选择的投票条目infoid={},ids={}",pid,voteItemIds);
      Long infoId = NumberUtils.toLong(pid);
      if (StringUtils.isNotBlank(voteItemIds)) {
        String[] idarr= StringUtils.split(voteItemIds,",");
        if(idarr!=null && idarr.length!=0){
          for(int i=0;i<idarr.length;i++){
            Long voteItemId = NumberUtils.toLong(StringUtils.strip(idarr[i]));
            InfoVoteLog entity = new InfoVoteLog();
            entity.setPersonnelId(personnelId);
            entity.setPerName(personnelName);
            entity.setEnterpriseId(enterpriseId);
            entity.setVoteItemId(voteItemId);
            entity.setVoteDate(new Date());
            entity.setInfoId(infoId);
            infoVoteLogService.save(entity);
          }
        }
        setResult(SUCCESS, "投票成功！");
        LogUtil.log("信息投票管理", LogUtil.ACTION_UPDATE, LogUtil.RESULT_SUCCESS, "参与投票");
      }
    } catch (Exception e) {
      if (StringUtils.isNotBlank(voteItemIds)) {
        LogUtil.log("信息投票管理", LogUtil.ACTION_UPDATE, LogUtil.RESULT_FAIL, "参与投票");
        logger.error("<错误>:参与投票异常{}", e);
      }
    }
    return JSON;
  }

  /**
   * 结束投票
   * 
   * @return
   */
  public String finishVote() {
    try {
      if (StringUtils.isNotBlank(id)) {
        logger.debug("<进入>:结束投票");
        Long infoId = NumberUtils.toLong(id);
        infomationService.finishVote(infoId);
        setResult(SUCCESS, "结束投票成功！");
        LogUtil.log("信息投票管理", LogUtil.ACTION_UPDATE, LogUtil.RESULT_SUCCESS, "新增信息");
      }
    } catch (Exception e) {
      if (StringUtils.isNotBlank(id)) {
        LogUtil.log("信息投票管理", LogUtil.ACTION_UPDATE, LogUtil.RESULT_FAIL, "修改信息");
        logger.error("<错误>:修改异常{}", e);
      }
    }
    return JSON;
  }

  /**
   * 重新投票
   * 
   * @return
   */
  public String restartVote() {
    try {
      if (StringUtils.isNotBlank(id)) {
        logger.info("<进入>:开始投票");
        Long infoId = NumberUtils.toLong(id);
        infomationService.startVote(infoId);
        setResult(SUCCESS, "开始投票成功！");
        LogUtil.log("信息投票管理", LogUtil.ACTION_UPDATE, LogUtil.RESULT_SUCCESS, "新增信息");
      }
    } catch (Exception e) {
      LogUtil.log("信息投票管理", LogUtil.ACTION_UPDATE, LogUtil.RESULT_FAIL, "修改信息");
      logger.error("<错误>:修改异常{}", e);
    }
    return JSON;
  }

  // /**
  // * 查看投票人员 建立日期 : May 31, 2014 5:00:24 PM<br>
  // * 作者 : 王阿敏<br>
  // *
  // * @param stringIds
  // */
  // public String votePersonal() {
  // logger.debug("<进入>:votePersonal方法 查看投票人员");
  // voteLoglist = infoVoteItemService.votePersonal(entity);
  // return "votePersonal";
  // }
  //
  // /**
  // * 新建投票 建立日期 : Apr 23, 2013 5:41:50 PM<br>
  // * 作者 : wangamin<br>
  // *
  // * @return
  // */
  // public String saveUpdateInfo() {
  // logger.debug("<进入>:saveUpdateInfo方法");
  // try {
  // Long enterpriseId = (Long) getSession().getAttribute("enterpriseId");
  // Personnel p = (Personnel) getSession().getAttribute("personnel");
  // String[] ids = null;
  // if (StringUtils.isNotBlank(itemids)) {
  // ids = itemids.split(",");
  // }
  // infoVoteLog.setEnterpriseId(enterpriseId);
  // infoVoteLog.setPerName(p.getName());
  // infoVoteLog.setPersonnelId(p.getPersonnelId());
  // infoVoteLog.setVoteDate(new Date());
  // inifid = infoVoteLog.getInfoId();
  // if (ids != null) {
  // for (int i = 0; i < ids.length; i++) {
  // infoVoteLog.setVoteItemId(Long.valueOf(ids[i].trim()));
  // infoVoteItemService.save(infoVoteLog);
  // infoVoteLog.setVoteLogId(null);
  // }
  // }
  // if (StringUtils.isBlank(itemids)) {
  // infoVoteItemService.save(infoVoteLog);
  // }
  // } catch (Exception e) {
  // logger.error("<错误>:投票错误", e);
  // }
  // return "voteColumn";
  // }

  public String getIds() {
    return ids;
  }

  public void setIds(String ids) {
    this.ids = ids;
  }

  public String getTreeNodes() {
    return treeNodes;
  }

  public void setTreeNodes(String treeNodes) {
    this.treeNodes = treeNodes;
  }

  public String getPid() {
    return pid;
  }

  public void setPid(String pid) {
    this.pid = pid;
  }

  public String getSearchName() {
    return searchName;
  }

  public void setSearchName(String searchName) {
    this.searchName = searchName;
  }

  public InformationView getView() {
    return view;
  }

  public void setView(InformationView view) {
    this.view = view;
  }

  public InfoColumn getBelongInfoColumn() {
    return belongInfoColumn;
  }

  public void setBelongInfoColumn(InfoColumn belongInfoColumn) {
    this.belongInfoColumn = belongInfoColumn;
  }

  public String getVoteItemIds() {
    return voteItemIds;
  }

  public void setVoteItemIds(String voteItemIds) {
    this.voteItemIds = voteItemIds;
  }

}
